const db = wx.cloud.database();
const dataPageNum = 6
var app = getApp();
Page({
  data: {
    color: app.ext.color,
    rankList: ["全部", "零售", "轻站"],
    orderType: 0, // 0："desc"降序   1："asc"升序
    orderBy: 'createtime', // "rank":综合 "sale":销量 "price":价格
    selectIndex: 0,
    search_text: '',
    product_list: [],
    is_all: 0,
    page: 1,
    dataNum: 0,
    dataPageNum: 9,
    isSearch: 0,
    loadCount: 0,
    showCount: 0,
    current: 'homepage',
    height: 0,
    avatar: [{ avatar_url: wx.getStorageSync("userInfo").avatarUrl}],
    avatar_total: 0,
    showTmpAvater:0,
    user_avatar_url: wx.getStorageSync("userInfo").avatarUrl,
    vcon: [{
      url: '../../../images/noimg2.png',
    }, {
      url: '../../../images/noimg2.png',
    }],
    indicatorDots: true,
    autoplay: true,
    duration: 500,
    interval: 3000,
    swiperHeight: 200,
    dz: 0,
    dz_total: 0,
    mbdata: [],
    lsmbdata: []
  },
  onLoad: function (options) {
   
    wx.getSystemInfo({
      success: (res) => {
        console.log(res.screenHeight);
        console.log(res.windowHeight);
        let h = res.windowHeight - 50;
        this.setData({
          height: h
        })

      }
    })
    this.setData({
      loadCount: this.data.loadCount + 1
    })
    if (options.text) {
      this.setData({
        search_text: options.text
      })
    }
    db.collection('swiper_url')
      .get()
      .then(res => {
        console.log(res.data);
        this.setData({
          vcon: res.data
        })
      })
      .catch(err => {
        console.error(err)
      })
    db.collection('user_info').orderBy('createtime', 'desc')
      .limit(6) // 限制返回数量为 6 条
      .get()
      .then(res => {
        console.log(res.data);
        if(res.data.length>0){
          if (res.data[0].avatar_url != wx.getStorageSync("userInfo").avatarUrl){
            this.setData({
              showTmpAvater:1
            })
          }
          this.setData({
            avatar: res.data
          })
        }
      })
      .catch(err => {
        console.error(err)
      })
    db.collection('user_info')
      .count().then(res => {
        this.setData({
          avatar_total: res.total 
        })
      });
    db.collection('user_list')
      .where({ dz: 1 })
      .count().then(res => {
        this.setData({
          dz_total: res.total
        })
      });
    db.collection('user_list').where({
      openid: wx.getStorageSync("openid") // 填入当前用户 openid
    }).get().then(
      res => {
        if(res.data.length>0)
        this.setData({
          dz: res.data[0].dz,
          user_avatar_url: wx.getStorageSync("userInfo").avatarUrl
        })
      }
    );
    db.collection('index_diy').where({
      type: 'template',
      product: '1'
    }).limit(this.data.dataPageNum).get().then(res => {
      if (res.data.length > 0) {
        this.setData({
          lsmbdata: res.data
        })
      }
    });
    db.collection('index_diy').where({
      type: 'template',
      product: '2'
    }).limit(this.data.dataPageNum).get().then(res => {
      if (res.data.length > 0) {
        this.setData({
          mbdata: res.data
        })
      }
    });

  },
  onShow: function () {
    this.setData({
      showCount: this.data.showCount + 1
    })
    if (this.data.showCount == this.data.loadCount) {
      this._clear();
      this.setData({
        dataNum: 0
      })
      this.getProducts(0);
    }
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.req == 1) {
      this._clear();
      this.setData({
        dataNum: 0
      })
      this.getProducts(0);
      this.setData({
        req: 0
      })
    }
  },
  _clear() {
    this.setData({
      page: 1,
      product_list: [],
      is_all: 0,
      orderType: 0,
      orderBy: 'createtime'
    })
  },
  bindconfirm(e) {
    this.data.search_text = e.detail;
    this._clear();
    this.getProducts(0);
  },
  getProducts(e) {
    let product_list = this.data.product_list;
    if ("" == this.data.search_text) {
      if (this.data.isSearch == 1)
        this.setData({
          dataNum: 0
        })
      if (e == 3) {
        this.setData({
          dataNum: 0
        })
      }
      if (this.data.selectIndex == 0) {   //查询零售和微站全部
        db.collection('index_diy').where({ _openid: wx.getStorageSync("openid"), type: 'user' }).orderBy(this.data.orderBy, this.data.orderType ? 'asc' : 'desc').skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
          console.log(res.data);
          this.data.page++;
          const DATA = res.data;
          product_list = product_list.concat(DATA);
          this.setData({
            dataNum: this.data.dataNum + dataPageNum
          })
          if (product_list.length != this.data.dataNum) this.data.is_all = 1;
          this.setData({
            page: this.data.page,
            is_all: this.data.is_all,
            product_list: product_list,
            orderType: this.data.orderType
          });
        })
      } else {
        console.log("sdfsdf")
        console.log(this.data.selectIndex)
        db.collection('index_diy').where({ _openid: wx.getStorageSync("openid"), type: 'user', product: this.data.selectIndex + "" }).orderBy(this.data.orderBy, this.data.orderType ? 'asc' : 'desc').skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
          console.log(res.data);
          this.data.page++;
          const DATA = res.data;
          product_list = product_list.concat(DATA);
          this.setData({
            dataNum: this.data.dataNum + dataPageNum
          })
          if (product_list.length != this.data.dataNum) this.data.is_all = 1;
          this.setData({
            page: this.data.page,
            is_all: this.data.is_all,
            product_list: product_list,
            orderType: this.data.orderType
          });
        })
      }

      this.setData({
        isSearch: 0
      })
    } else {
      if (this.data.isSearch == 0) {
        this.setData({
          dataNum: 0
        })
      } else {
        if (e != 2) {
          this.setData({
            dataNum: 0
          })
        }
      }
      if (e == 3) {
        this.setData({
          dataNum: 0
        })
      }
      if (this.data.selectIndex == 0) {
        db.collection('index_diy').where({ _openid: wx.getStorageSync("openid"), type: 'user' }).orderBy(this.data.orderBy, this.data.orderType ? 'asc' : 'desc').skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
          console.log(res);
          const DATA = res.data;
          let mData = [];
          var reg = new RegExp(this.data.search_text);
          for (var i = 0; i < DATA.length; i++) {
            if (DATA[i].name.match(reg)) {
              mData.push(DATA[i])
            }
          }

          this.data.page++;

          product_list = product_list.concat(mData);
          this.setData({
            dataNum: this.data.dataNum + dataPageNum
          })
          if (product_list.length != this.data.dataNum) this.data.is_all = 1;
          this.setData({
            page: this.data.page,
            is_all: this.data.is_all,
            product_list: product_list,
            orderType: this.data.orderType
          });
        })
      } else {
        db.collection('index_diy').where({ _openid: wx.getStorageSync("openid"), type: 'user', product: this.data.selectIndex + "" }).orderBy(this.data.orderBy, this.data.orderType ? 'asc' : 'desc').skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
          console.log(res);
          const DATA = res.data;
          let mData = [];
          var reg = new RegExp(this.data.search_text);
          for (var i = 0; i < DATA.length; i++) {
            if (DATA[i].name.match(reg)) {
              mData.push(DATA[i])
            }
          }

          this.data.page++;

          product_list = product_list.concat(mData);
          this.setData({
            dataNum: this.data.dataNum + dataPageNum
          })
          if (product_list.length != this.data.dataNum) this.data.is_all = 1;
          this.setData({
            page: this.data.page,
            is_all: this.data.is_all,
            product_list: product_list,
            orderType: this.data.orderType
          });
        })
      }

      this.setData({
        isSearch: 1
      })
    }

  },
  // 切换商品展示状态
  switch_type(e) {
    const type = e.currentTarget.dataset.type;
    // show_type 0：块状 1：列表
    this.setData({
      show_type: type
    });
  },
  changeRank(e) {
    const index = Number(e.currentTarget.dataset.index);
    const type = Number(e.currentTarget.dataset.order_type);
    this.setData({
      page: 1,
      product_list: [],
      is_all: 0,
      selectIndex: index
    })
    this.getProducts(3);
  },
  goProductDetail: function (e) {
    console.log(e.currentTarget.dataset.id);

    wx.navigateTo({

      url: `/pages/shop/product/product-detail/index?id=${e.currentTarget.dataset.id}`
    });
  },
  onPullDownRefresh: function () {
    setTimeout(() => {
      this._clear();
      this.getProducts(1);
      wx.stopPullDownRefresh();
    }, 500)
  },
  onReachBottom: function () {
    if (!this.data.is_all) {
      this.getProducts(2);
    }
  },
  onAddProduct: function (e) {
    db.collection('index_diy').where({
      _openid: wx.getStorageSync("openid") // 填入当前用户 openid
    }).count().then(res => {
      console.log(res.total)
      if (res.total > 2) {
        wx.showToast({
          icon: 'none',
          title: '最多免费拥有2个模板哦',
        });
      } else {
        wx.navigateTo({
          url: `/pages/manage/xcx-add/index`
        });
      }
    })

  },
  onClickDel(e) {
    const that = this;
    db.collection('index_diy').doc(e.currentTarget.dataset.id).remove({
      success(res) {
        if (res.errMsg == "document.remove:ok") {
          that._clear();
          that.setData({
            dataNum: 0
          })
          that.getProducts(0);
          wx.showToast({
            title: '数据已被删除',
          });
        } else {
          wx.showToast({
            title: '数据删除失败',
          });
        }

      },
      fail: console.error
    })
  },
  onClickUpt(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id)
    wx.navigateTo({
      url: `/pages/manage/template-add/index?id=` + e.currentTarget.dataset.id
    });
  },
  onClickDiy(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id);
    app.globalData.diyId = e.currentTarget.dataset.id;
    app.globalData.diyProduct = e.currentTarget.dataset.product;
    app.globalData.diyPageI = -1;
    app.globalData.diyEdit = "true";
    wx.navigateTo({
      url: `/pages/com/home/index`
    });
  },
  onClickMan(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id);
    app.globalData.diyId = e.currentTarget.dataset.id;
    app.globalData.diyProduct = e.currentTarget.dataset.product;
    wx.navigateTo({
      url: `/pages/manage/nav/index`
    });
  },
  onClickView(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id)


          app.globalData.diyId = e.currentTarget.dataset.id;
          app.globalData.diyProduct = e.currentTarget.dataset.product;
          app.globalData.diyPageI = -1;
          app.globalData.diyEdit = "false";
          if (e.currentTarget.dataset.product == 1) {
            wx.switchTab({
              url: `/pages/com/index/index`
            });
          } else {
            wx.navigateTo({
              url: `/pages/com/home/index`
            });
          }

        
      

  },
  onClickMainView(e) {
    console.log(123);
    wx.setStorageSync('diyId', e.currentTarget.dataset.id)
    app.globalData.diyId = e.currentTarget.dataset.id;
          app.globalData.diyProduct = e.currentTarget.dataset.product;
          app.globalData.diyPageI = -1;
          app.globalData.diyEdit = "false";
          if (e.currentTarget.dataset.product == 1) {
            wx.switchTab({
              url: `/pages/com/index/index`
            });
          } else {
            wx.navigateTo({
              url: `/pages/com/home/index`
            });
          }
    // db.collection('index_diy').where({
    //   _id: e.currentTarget.dataset.id
    // }).get({
    //   success(res) {
    //     if ((res.data[0].all.length == 1 && res.data[0].product == "2") || (res.data[0].all.length == 0 && res.data[0].product == "1")) {
    //       wx.showToast({
    //         icon: "none",
    //         title: '正在努力设计中',
    //         duration: 2000
    //       })
    //     } else {
          

    //     }
    //   }
    // })
  },
  handleChange({ detail }) {
    console.log(detail)
    this.setData({
      current: detail.key
    });
    // if (detail.key =='homepage'){
    //   app.globalData.diyId = '';
    //   app.globalData.diyProduct = '';
    //   app.globalData.diyPageI = -1;
    //   app.globalData.diyEdit = "false";
    //   wx.redirectTo({
    //     url: `/pages/com/home/index`});
    // }
  },
  onClickDz(e) {
    this.setData({
      dz: 1,
      dz_total: this.data.dz_total + 1
    })
    wx.cloud.callFunction({
      // 云函数名称
      name: 'user-add',
      // 传给云函数的参数
      data: {
        dz: 1,
        openid: wx.getStorageSync('openid')
      },
      complete: res => {
        console.log('callFunction test result: ', res);
      }
    })
  },
  onClickQxDz(e) {
    this.setData({
      dz: 0,
      dz_total: this.data.dz_total - 1
    });
    wx.cloud.callFunction({
      // 云函数名称
      name: 'user-add',
      // 传给云函数的参数
      data: {
        dz: 0,
        openid: wx.getStorageSync('openid')
      },
      complete: res => {
        console.log('callFunction test result: ', res);
      }
    })
  },
  onClickMbMore(e) {
    wx.navigateTo({
      url: '../../../pages/manage/template-man/index'
    });
  }
})